package com.vf.cloud.paas.app.master.api.render.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.jfinal.kit.JsonKit;
import com.vf.cloud.paas.app.master.common.domain.Project;
import com.vf.cloud.paas.app.master.common.domain.RenderAgent;
import com.vf.cloud.paas.app.master.common.domain.RenderAgentGpu;
import com.vf.cloud.paas.common.cirrus.Cirrus;
import com.vf.cloud.paas.common.datasource.annotation.Tx;
import com.vf.cloud.paas.common.log.annotation.RLog;
import com.vf.cloud.paas.common.security.annotation.TokenRequired;
import com.vf.cloud.paas.common.service.IRedis;
import com.vf.cloud.paas.common.util.R;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/render/agent/gpu")
public class RenderAgentGpuController {

	@Autowired
	private IRedis redisImpl;

	@RLog(value = "重置GPU", type = "user")
	@TokenRequired
	@Tx
	@RequestMapping(value = "/syn", method = RequestMethod.POST)
	public R<String> restart(HttpServletRequest request, @RequestBody RenderAgent param) {
		try {
			RenderAgent renderAgent = RenderAgent.dao.findById(param.getId());
			if (renderAgent == null) {
				return R.failed("节点不存在.");
			}
			ChannelHandlerContext ctx = Cirrus.AgentManager.get(renderAgent.getId());
			if (ctx == null) {
				return R.failed("节点掉线中,稍后再试.");
			}

			List<RenderAgentGpu> renderAgentGpus = RenderAgentGpu.dao.find(
					"select a.id,a.index,a.limit from " + RenderAgentGpu.TABLE_NAME + " a where a.agent_id=?",
					renderAgent.getId());

			for (RenderAgentGpu gpu : renderAgentGpus) {
				Set<String> keys = redisImpl.getByUuidPrefix(gpu.getId());
				redisImpl.delete(keys);
			}

			List<Project> projects = Project.dao.find(
					"select id,exe_relative_path from " + Project.TABLE_NAME
							+ " where id in (select project_id from master_project_syn_status where agent_id=? )",
					param.getId());

			Map<String, Object> clientConfig = new HashMap<String, Object>();
			clientConfig.put("type", "SynForGPU");
			clientConfig.put("gpus", renderAgentGpus);
			clientConfig.put("projects", projects);
			clientConfig.put("agentId", renderAgent.getId());
			String mm = JsonKit.toJson(clientConfig);

			ctx.channel().writeAndFlush(new TextWebSocketFrame(mm)).addListener(new ChannelFutureListener() {
				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					if (future.isSuccess()) {
						// log.info(String.format("-> Streamer:%s", mm));
					} else {
						// log.info(String.format("-> Streamer isError :%s", mm));
					}
				}
			});

			return R.ok();
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

}
